package com.kingland.springbootstarterdataredis.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/redisData")
public class RedisData {

    @Autowired
    StringRedisTemplate redisTemplate;


    /**
     * View all data in the current Redis
     */
    @GetMapping("getAll")
    public String getAllRedisData() {
        Set<String> keys = redisTemplate.keys("*");
        assert keys != null;
        List<String> values = redisTemplate.opsForValue().multiGet(keys);
        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < keys.size(); i++) {
            assert values != null;
            stringBuilder.append(keys.toArray()[i]).append(": ").append(values.get(i)).append("\n");
        }
        return stringBuilder.toString();
    }

    /**
     * Set the key value
     */
    @GetMapping("/set/{key}/{value}")
    public String setData(@PathVariable String key, @PathVariable String value) {
        redisTemplate.opsForValue().set(key, value);
        return "Key: " + key + " Value: " + value + " has been saved";
    }

    /**
     * Obtain the value based on the key
     */
    @GetMapping("/get/{key}")
    public String getValueByKey(@PathVariable String key) {
        String value = redisTemplate.opsForValue().get(key);
        if (value != null) {
            return "Key: " + key + " Value: " + value;
        } else {
            return "Key not found, please set key-value first, api -> /redisData/set/$key/$value";
        }
    }

    /**
     * Delete the value based on the key
     */
    @GetMapping("/delete/{key}")
    public String delete(@PathVariable String key) {
        redisTemplate.delete(key);
        return "Key: " + key + " has been deleted";
    }
}
